package cn.donting.jme.texture;

import com.jme3.asset.AssetInfo;
import com.jme3.asset.AssetLoader;
import com.jme3.texture.Texture;
import com.jme3.util.blockparser.BlockLanguageParser;
import com.jme3.util.blockparser.Statement;

import java.io.IOException;
import java.util.List;

public class TextureLoader implements AssetLoader {

    @Override
    public Object load(AssetInfo assetInfo) throws IOException {
        List<Statement> parse = BlockLanguageParser.parse(assetInfo.openStream());
        Statement statement = parse.get(0);
        String line = statement.getLine();
        List<Statement> contents = statement.getContents();
        Texture texture = assetInfo.getManager().loadTexture(line.trim());
        texture.setKey(assetInfo.getKey());
        readParam(contents,texture);
        return texture;
    }

    private void readParam(List<Statement> contents, Texture texture) throws IOException {
        for (Statement content : contents) {
            String line = content.getLine();
            String[] split = line.split(":");
            String name = split[0].trim();
            String value = split[1].trim();
            setParam(name, value, texture);
        }
    }

    private void setParam(String name, String value, Texture texture) throws IOException {
        switch (name) {
            case "wrap": {
                texture.setWrap(Texture.WrapMode.valueOf(value));
                return;
            }
            case "minFilter": {
                texture.setMinFilter(Texture.MinFilter.valueOf(value));
                return;
            }
            case "magFilter": {
                texture.setMagFilter(Texture.MagFilter.valueOf(value));
                return;
            }
            case "shadowCompareMode": {
                texture.setShadowCompareMode(Texture.ShadowCompareMode.valueOf(value));
                return;
            }
        }
        throw new IOException(name + ":" + value + " is not support");
    }
}
